﻿
//		loadingImage: '/Content/Images/loading.gif'
//		containerTag: 'div'
//		ajaxUrl: '/'
//		ajaxMethod: 'GET'
//		clearContent: false
//		onOverlayOpen: function () { }
//		onOverlayClose: function () { }
//		onAjaxSuccess: function (data) { }
//		onAjaxError: function (data) { }


(function ($) {

	$.fn.ajaxLoading = function (options) {

		options = $.extend({}, $.fn.ajaxLoading.defaults, options);

		var $this = this;

		return $this.each(function () {

			var loadingElement = null;
			var loadingHtml = '<' + options.containerTag
						+ ' style="background: url(' + options.loadingImage + ')'
						+ ' no-repeat center; position:absolute; top:0px; left:0px; width:100%; height:100%;" title="Loading....">'
						+ '</' + options.containerTag + '>';

			ShowLoadingOverlay();

			function ShowLoadingOverlay() {

				loadingElement = $(loadingHtml);

				if (typeof options.onOverlayOpen == 'function') {
					options.onOverlayOpen.call();
				}

				if (options.clearContent) {
					loadingElement.html('');
				}

				loadingElement.appendTo($this).overlay({

					top: '50%',
					left: '50%',
					closeOnClick: false,
					load: false,
					mask: { loadSpeed: 200, color: '#005589', opacity: 0.5 }
				});

				SubmitAjax();
			}

			function SubmitAjax() {
				$.ajax({
					url: options.ajaxUrl,
					type: options.ajaxMethod,
					success: AjaxSuccess,
					error: AjaxError
				});
			}

			function AjaxSuccess(data) {
				if (typeof options.onAjaxSuccess === 'function') {
					options.onAjaxSuccess(data);
				}

				RemoveLoadingOverlay();
				$this.html(data);
			}

			function RemoveLoadingOverlay() {
				if (typeof options.onOverlayClose === 'function') {
					options.onOverlayClose.call();
				}

				$(loadingElement).remove();
			}

			function AjaxError(data) {
				if (typeof options.onOverlayClose === 'function') {
					options.onAjaxError(data);
				}

				alert('We apologize for the inconvenience, but an error occured. \n Error Code: "' + data.statusText + '".');
			}
		});
	};

	$.fn.ajaxLoading.defaults = {
		loadingImage: '/Content/Images/loading.gif',
		containerTag: 'div',
		ajaxUrl: '/',
		ajaxMethod: 'GET',
		clearContent: false,
		onOverlayOpen: function () { },
		onOverlayClose: function () { },
		onAjaxSuccess: function (data) { },
		onAjaxError: function (data) { }
	};

})(jQuery);